<template>
  <div class="app-container">
    <!-- <el-button type="text" @click="dialogVisible = true">添加</el-button> -->
    <!-- <el-card shadow="never"> -->
      <!-- <div slot="header" style="text-align: center;">店铺列表</div> -->
      <!-- 搜索黑名单 -->
            <div style="margin-bottom: 10px;">
              <el-form>
                <el-row class="rowFormItem">

                 <el-col :span="3">
                   <el-select filterable clearable v-model="merchant_id" placeholder="门店名称">
                     <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
                   </el-select>
                 </el-col>
                  <!-- 提交按钮 -->
                  <el-col :span="4" class="clear">
                    <el-button style="margin-left: 10px;" @click="handleReset()">重置</el-button>
                    <el-button type="success" @click="addmodel">添加</el-button>
                  </el-col>
                </el-row>
              </el-form>
            </div>

      <div class="tableClass">
        <el-table :data="formdata" v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          border style="width: 100%;">
          <el-table-column align="center" prop="id" label="序号" />
          <el-table-column align="center" prop="name" label="名称" />
          <!--<el-table-column align="center" prop="back_img" label="专区背景图片">
            <template slot-scope="scope">
                <el-button type="text" size="medium">
                  <img style="width: 50%;" :src="scope.row.img_url" />
                </el-button>
              </template>
          </el-table-column>-->
          <!-- <el-table-column align="center" prop="website" label="关联商品分类" />
          <el-table-column align="center" prop="contact" label="关联商品数量" /> -->
          <el-table-column align="center" prop="merchant_name" label="门店" />
          <el-table-column align="center" prop="sort" label="排序" />
          <el-table-column label="操作" align="center" width="280px">
            <template slot-scope="scope">
              <!-- scope.row 获取整行信息 表示当前单元格 #ff9900ba-->
              <el-button class="btnAppeal" size="small" type="primary" @click="associated(scope.row.id,scope.row.merchant_id)">关联商品</el-button>
              <el-button class="btnAppeal" size="small" type="warning" @click="updateMsg(scope.row.id)">修改</el-button>
              <el-button class="btnAppeal" size="small" type="danger" @click="delMsg(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <br>
        <!-- 分页 -->
        <div style="text-align: center;">
          <el-pagination background layout="prev, pager, next" :current-page="startpage" @current-change="pageChange" :page-size="pageSize"
            :total="totalusers" />
        </div>
      </div>
    <!-- </el-card> -->


    <!-- 添加模态款 -->
    <el-dialog style="margin: auto;overflow: hidden" :title="title" :visible.sync="modelMsg">
      <div class="msgDiv">
        <!-- <h3>店铺基础信息</h3> -->
        <div>
          <el-form ref="form" :model="form" label-width="140px" label-position="right">
            <el-form-item v-show="vshow" label="序号">
              <el-input v-model="form.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="名称" :required="true">
              <el-input v-model="form.name" placeholder="请输入名称"></el-input>
            </el-form-item>
            <!-- <el-form-item label="商品分类" :required="true">
              <el-input v-model="form.sortnum" placeholder="请选择商品分类"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" :required="true">
              <el-input v-model="form.sortnum" placeholder="请选择商品数量"></el-input>
            </el-form-item> -->
            <el-form-item label="门店" :required="true" style="text-align: left;">
              <el-select v-model="form.merchant_name" placeholder="门店名称" @change="changeMarchant">
                <el-option v-for="item in options" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>

            <el-form-item label="排序" :required="true">
              <el-input v-model="form.sort" placeholder="请输入顺序排序"></el-input>
            </el-form-item>
            <!-- 封面图片 -->
           <!-- <el-form-item label="专区背景图" style="text-align: left;">
              <el-tooltip placement="top">
                <div slot="content">请上传图片</div>
                <i class="el-icon-info" style="font-size: 18px;"></i>
              </el-tooltip>
              <el-upload class="avatar-uploader" :action="$api.UPLOAD_IMG" name='photo'
                         :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <el-image :fit="'scale-down'" v-if="form.imageUrl" :src="form.imageUrl" class="avatar"></el-image>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>-->
            <!-- 封面图片end -->

            <el-form-item label="专区广告图" style="text-align: left">
              <el-upload
                class="avatar-uploader"
                name="photo"
                :action="$api.UPLOAD_IMG"
                :show-file-list="false"
                :on-success="addUploadSuccess"
              >
                <img v-if="addForm.imgUrl" :src="addForm.imgUrl" style="object-fit:contain" class="avatar">
                <div v-else style="display: flex;align-items: center;flex-direction: column;font-size: 11px;color: grey;line-height: 15px;padding-bottom: 10px" >
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                  <span>宽高比例不受限制</span>
                  <span>文件大小<2Mb</span>
                </div>
              </el-upload>
            </el-form-item>

          </el-form>

          <el-form ref="form" :model="form" label-width="140px" label-position="left">
            <el-form-item label="专区广告图跳转链接">
              <el-input v-model="addForm.link" auto-complete="off" placeholder="请输入网页链接或appid"></el-input>
              <div class="" style="text-align: left">
                <el-checkbox v-model="isDefaultPath">跳转专区商品页面</el-checkbox>
              </div>
            </el-form-item>
          </el-form>

          <el-button type="success" @click="addMsg(form)">{{addORupdate}}</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 关联商品model -->
    <el-dialog width="60%" title="关联商品" :visible.sync="goodModel" >
      <div class="msgDiv">
        <div style="display: flex;">
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item v-show="false" label="序号">
              <el-input v-model="goods.merchant_medicine_area_id" disabled></el-input>
            </el-form-item>
            <el-form-item label="商品" :required="true" style="text-align: left;">
               <el-select filterable clearable  v-model="goods.merchant_medicine_id" placeholder="商品名称" :filter-method="selectGoodsChange">
                 <el-option v-for="(item,index) in goodsList" :key="index" :label="item.label" :value="item.id" />
               </el-select>
            </el-form-item>
          </el-form>
          <el-button style="height: 40px;margin-left: 10px;" type="success" @click="banddingShop(goods)">绑定</el-button>
        </div>
        <el-table :data="banddingList" v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          border>
          <el-table-column align="center" prop="id" label="序号" />
          <el-table-column align="center" prop="goods_name" label="名称" />
          <el-table-column align="center" prop="goods_thumb_url" label="图片">
            <template slot-scope="scope">
                <el-button type="text" size="medium">
                  <img style="width: 30%;" :src="scope.row.goods_thumb_url" />
                </el-button>
              </template>
          </el-table-column>

          <el-table-column label="操作" align="center" >
            <template slot-scope="scope">
              <!-- scope.row 获取整行信息 表示当前单元格 #ff9900ba-->
              <el-button class="btnAppeal" size="small" type="danger" @click="delShopMsg(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination style="margin-top: 10px;" background :current-page="banddingPage" layout="prev, pager, next" @current-change="baddingPageChange" :page-size="5" :total="banddingTotal" />
        <br />
        <!--<div style="margin-top: 10px;">
          <el-button type="primary" @click="goodModel = false">关闭</el-button>
        </div>-->
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    watch: {
      merchant_id(val){
        this.startpage = 1
        this.getMerchantMedicineAreaList()
      },
      "addForm.link"(val){
        if(this.form.id && (val.indexOf('pages/goodsList/goodList')==-1 || val.indexOf('type=shop')==-1)){
          this.isDefaultPath = false
        }
      }
    },
    data() {
      return {
        modelMsg: false,
        form: {
          id: "",
          name: "",
          sort: "",
          img_id: "",
          merchant_id:"",
          merchant_name:"",
          imageUrl: "",
        },
        addForm: {
          location: "x",
          imgUrl: '',
          imgId: '',
          link: '',
          desc: ''
        },
        merchant_id:"",//搜索的merchant_id
        shopMerchant_id:"",
        options: [],
        vshow: false,
        goodModel:false, //绑定商品model
        goods:{
          merchant_medicine_id:"",
          merchant_medicine_area_id:""
        },
        goodsList:[],
        banddingList:[],
        loading: false,
        title: "",
        addORupdate: "", //添加或修改
        formdata: [],
        totalusers: 0, //总行数
        pageSize: 5, //每页几行
        startpage: 1, //起始页
        ad_info: '',
        isDefaultPath: false,
        banddingPage: 1,
        banddingTotal: 0,
        currentAreaId: ''
      }
    },
    mounted() {
      this.getMerchantMedicineAreaList()
      this.getMerchantScreenList()
    },
    methods: {


      selectGoodsChange(e) {
        this.getGoodsList(e)
      },

      //提交绑定商品
      banddingShop(goods){
        if(goods.merchant_medicine_id == ""){
          this.$message.warning("请选择需要绑定的商品")
          return false
        }
        /* 显示加载中。。。 */
        const loadingOne = this.$loading({
          lock: true,
          text: '保存中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
          this.$api.setMerchantMedicineXArea(goods).then(res=>{
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              let id = window.localStorage.getItem("merchant_medicine_area_id")
              this.banddingPage = 1
               this.getMerchantMedicineXAreaListFANGfa(id)
              loadingOne.close()
            } else {
              loadingOne.close()
            }
          })
      },

      //关联商品
      associated(id,merchant_id){
          this.goodModel = true
          this.goods.merchant_medicine_id = ""
          this.goods.merchant_medicine_area_id = id
          this.shopMerchant_id = merchant_id
          this.currentAreaId = id
          window.localStorage.setItem("merchant_medicine_area_id",id)
          this.banddingPage = 1
          this.getMerchantMedicineXAreaListFANGfa(id)
          this.getGoodsList()
      },

      //获取专区绑定的商品列表
      getMerchantMedicineXAreaListFANGfa(id){
          let params = {
            "page": this.banddingPage,
            "limit":5,
            "merchant_medicine_area_id":this.currentAreaId
          }
          this.$api.getMerchantMedicineXAreaList(params).then(res => {
            this.banddingList = res.data.data
            this.banddingTotal = res.data.page_info.total
          })
      },

      async baddingPageChange(page) {
        this.banddingPage = page
        //调用获取列表的方法
        this.getMerchantMedicineXAreaListFANGfa()
      },

      //获取商品列表
      getGoodsList(keyword) {
        this.goodsList = []
        let params = {
          "page": 1,
          "limit":8,
          "merchant_id":this.shopMerchant_id,
          "keyword": keyword
        }
        //调用后台提供的接口方法
        this.$api.getGoodsList(params).then(res => {
          res.data.data.forEach(item=>{

            let option = {
               "id":item.id,
               "label":item.name
            }
             this.goodsList.push(option)
          })
        })
      },
      //获取门店列表
      getMerchantScreenList() {
        let params = {
          "page": 1,
          "limit":100000
        }
        //调用后台提供的接口方法
        this.$api.getMerchantScreenList(params).then(res => {
          res.data.data.forEach(item=>{

            let option = {
               "id":item.id,
               "label":item.name
            }
             this.options.push(option)
          })

        })
      },

      //重置
      handleReset(){
        this.merchant_id = ""
        this.startpage = 1
        this.getMerchantMedicineAreaList()
      },

      //搜索
      handleSubmit(){
        this.startpage = 1
        this.getMerchantMedicineAreaList()
      },

      //获取分页列表
      getMerchantMedicineAreaList() {
        let params = {
          "page": this.startpage,
          "limit": this.pageSize,
          "merchant_id":this.merchant_id
        }
        //调用后台提供的接口方法
        this.$api.getMerchantMedicineAreaList(params).then(res => {
          if(res.data.level=="success"){
            this.formdata = res.data.data
            this.totalusers = res.data.page_info.total
            this.loading = false
          }else{
            this.$message.error(res.data.message)
          }

        })
      },

      //分页 pageChange当前页发生改变触发函数
      async pageChange(page) {
        this.startpage = page
        this.loading = true
        //调用获取列表的方法
        this.getMerchantMedicineAreaList()
      },

      //改变选中框的值时赋值
      changeMarchant(){
          this.form.merchant_id = this.form.merchant_name
      },

      addmodel() {
        this.modelMsg = true
        this.title = '添加专区信息'
        this.addORupdate = "添加",
          this.vshow = false
        this.form.id="",
        this.form.name= "",
        this.form.sort= "",
        this.form.img_id= "",
        this.form.merchant_id="",
        this.form.merchant_name="",
        this.form.imageUrl= ""
        this.addForm.desc = ''
        this.addForm.id = ''
        this.addForm.location = 'x'
        this.addForm.imgUrl = ''
        this.addForm.link = ''
        this.isDefaultPath = false
      },

      //提交店铺入驻申请
      async addMsg(form) {

        //判断带星号的是否为空
       /*if ((form.name && form.sort && form.img_id) == "") {
          this.$message({
            message: "带星号为必填项，请完善信息！",
            type: "warning"
          })
          return false;
        }*/

          /* 显示加载中。。。 */
          const loadingOne = this.$loading({
            lock: true,
            text: '保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })

          let responseRes = ''

          if (form.id > 0) {
            /* 修改 */
            await this.$api.setMerchantMedicineArea(form).then(res => {
              this.$message({
                type: res.data.level,
                message: res.data.message
              });
              if (res.data.level == "success") {
                this.getMerchantMedicineAreaList()
                loadingOne.close()
                this.modelMsg = false
                this.setAdImage(form)
              } else {
                loadingOne.close()
              }
            })
          } else {
            /* 添加 */
            await this.$api.setMerchantMedicineArea(form).then(res => {
              this.$message({
                type: res.data.level,
                message: res.data.message
              });
              if (res.data.level == "success") {
                this.getMerchantMedicineAreaList()
                loadingOne.close()
                this.setAdImage(res.data.data)
                this.modelMsg = false
              } else {
                loadingOne.close()
              }

            })
          }


      },


      async setAdImage(responseRes) {
        if (!responseRes) {
          return
        }
        console.log('aaa',this.isDefaultPath)
        if(this.isDefaultPath == true){
          this.addForm.link = `/pages/goodsList/goodList?areaId=${responseRes.id}&name=${responseRes.name}&type=shop`
        }

        await this.$api.setAdImage({
          merchant_id: responseRes.merchant_id,
          id: this.addForm.id,
          location: this.addForm.location,
          link: this.addForm.link,
          img_id: this.addForm.img_id,
          sort: responseRes.id,
          desc: this.addForm.desc,
          status: '1',
        }).then(res => {
          if (res.data.level === 'success') {
            this.addForm.img_id = "";
            this.addForm.desc = "";
            this.addForm.link = "";
          }
        })
      },

      //修改弹出框
      updateMsg(id) {
        this.modelMsg = true
        this.title = '修改专区信息'
        this.addORupdate = "修改",
        this.vshow = true
        let dataid = {
          "id":id
        }
        this.$api.getMerchantMedicineAreaDetail(dataid).then(res=>{
          let data = res.data.data
          this.form.id = data.id,
          this.form.name = data.name,
          this.form.sort = data.sort,
          this.form.merchant_id = data.merchant_id,
          this.form.merchant_name = data.merchant_name,
          this.form.img_id = data.img_id,
          this.form.imageUrl = data.img_url
          /*this.ad_info = data.ad_info*/

          if(!data.ad_info){
            this.addForm.desc = ''
            this.addForm.id = ''
            this.addForm.location = 'x'
            this.addForm.imgUrl = ''
            this.addForm.link = ''
            this.addForm.img_id = ''
            this.isDefaultPath = false
            return
          }
          let ad_info = data.ad_info
          this.addForm.desc = ad_info.desc
          this.addForm.id = ad_info.id
          this.addForm.location = 'x'
          this.addForm.imgUrl = ad_info.img_url
          this.addForm.img_id = ad_info.img_id
          this.addForm.link = ad_info.link
          if(this.addForm.link.indexOf('pages/goodsList/goodList')!=-1 && this.addForm.link.indexOf('type=shop')!=-1){
            this.isDefaultPath = true
          } else {
            this.isDefaultPath = false
          }
        })

      },

      //删除绑定商品信息
      async delShopMsg(id) {
        let delid = {
          id: id
        }
        await this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {

          this.$api.delMerchantMedicineXArea(delid).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            if (res.data.level == "success") {
             let id = window.localStorage.getItem("merchant_medicine_area_id")
              this.banddingPage = 1
              this.getMerchantMedicineXAreaListFANGfa(id)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      //删除店铺信息
      async delMsg(id) {
        let delid = {
          id: id
        }
        await this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {

          this.$api.delMerchantMedicineArea(delid).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            if (res.data.level == "success") {
              this.getMerchantMedicineAreaList()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      //图片上传
      handleAvatarSuccess(res, file) {
        //console.log(res.data.id)
        this.form.img_id = res.data.id
        //console.log(file)
        this.form.imageUrl = res.data.img_url;
      },

      //新增上传图片成功回调
      addUploadSuccess(res, file) {
        if(res.data){
          this.addForm.imgUrl = res.data.img_url;
          this.addForm.img_id = res.data.id;
        }
      },

      //验证图片格式
      beforeAvatarUpload(file) {
        /*const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;*/
      },
    }
  }
</script>
<style scoped="scoped">
  /deep/.el-card__header {
    background-color: #409EFF;
    color: whitesmoke;
  }

  /deep/.el-dialog {
    margin-top: 10vh !important;
    width: 40%;
  }



  .msgDiv {
    /*width: 50%;*/
    margin: auto;
    text-align: center;
  }

  .el-input {
    display: flex;
    flex-grow: <2>;
  }

  /* 图片上传css */
  .avatar-uploader /deep/.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    /*height: 100px;*/
    display: block;
  }

</style>
